package weaver.interfaces.dsjj.duss;

import com.weaver.general.BaseBean;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetDataSource;
import weaver.docs.webservices.DocAttachment;
import weaver.docs.webservices.DocInfo;
import weaver.docs.webservices.DocServiceImpl;
import weaver.general.StaticObj;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.interfaces.datasource.DataSource;

import java.io.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * @Title: ecology-9-demo
 * @Company: 泛微软件
 * @author: weaver.Dusongsong
 * @version: 1.0
 * @CreateDate: 2020-06-07
 * @Description: 转换方法
 * @ModifyLog:
 **/

public class TransMethod {
    // ID和GUID转换
    public static String transIDtoGUID(String id) {
        if (!"".equals( id ) || id != null) {
            RecordSet rs = new RecordSet();
            rs.executeQuery( "select textfield1 from hrmresource where id='" + id + "'" );
            rs.next();
            String textfield1 = Util.null2String( rs.getString( "textfield1" ) );
            textfield1 = textfield1.equals( "" ) ? "" : textfield1;
            return textfield1;
        } else {
            return "";
        }
    }

    // ID和GUID转换
    public static String HRtransGUIDtoID(String guid) {
        if (!"".equals( guid ) || guid != null) {
            RecordSet rs = new RecordSet();
            rs.executeQuery( "select id from hrmresource where textfield1='" + guid + "'" );
            rs.next();
            String id = Util.null2String( rs.getString( "id" ) );
            id = id.equals( "" ) ? "" : id;
            return id;
        } else {
            return "";
        }

    }


    //部门转换方法
    public static String bmTransMethod(String param) {
        RecordSet rs = new RecordSet();
        rs.executeQuery( "select id,departmentname from HrmDepartment where id='" + param + "'" );
        if (rs.next()) {
            String departmentname = Util.null2String( rs.getString( "departmentname" ) );
            return departmentname;
        } else {
            return "";
        }
    }

    //部门转换方法
    public static String bmIdTransMethod(String param) {
        RecordSet rs = new RecordSet();
        rs.executeQuery( "select departmentid,textfield1 from hrmresource where textfield1='" + param + "'" );
        if (rs.next()) {
            String departmentid = Util.null2String( rs.getString( "departmentid" ) );
            return departmentid;
        } else {
            return "";
        }
    }

    //姓名转换方法
    public static String nameTransMethod(String param) {
        RecordSet rs = new RecordSet();
        rs.executeQuery( "select textfield1,lastname from hrmresource where textfield1='" + param + "'" );
        if (rs.next()) {
            String lastname = Util.null2String( rs.getString( "lastname" ) );
            return lastname;
        } else {
            return "";
        }
    }

    //姓名转换方法
    public static String transIDtoLastname(String param) {
        RecordSet rs = new RecordSet();
        rs.executeQuery( "select id,lastname from hrmresource where id='" + param + "'" );
        if (rs.next()) {
            String lastname = Util.null2String( rs.getString( "lastname" ) );
            return lastname;
        } else {
            return "";
        }
    }

    //获取当前年月
    public static String getCurYearAndMonth() {
        Calendar cal = Calendar.getInstance();
        Date d = cal.getTime();
        SimpleDateFormat sp = new SimpleDateFormat( "yyyyMMdd" );
        String yesterday = sp.format( d );//昨天日期
        String ym = yesterday.substring( 0, 6 );
        return ym;
    }

    //随机获取一个大写字母
    public static char getRandomChar() {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        char randomChar = chars.charAt( (int) (Math.random() * 26) );
        return randomChar;
    }

    //十六进制转成文件
    public static void hexToFile(String hex, String filePath) {
        StringBuilder sb = new StringBuilder();
        sb.append( hex );
        saveToFile( sb.toString().toUpperCase(), filePath );
    }

    //hex 转为文件
    public static void saveToFile(String src, String output) {
        if (src == null || src.length() == 0) {
            return;
        }
        try {
            File file = new File( output );
            FileOutputStream out = new FileOutputStream( file );
            byte[] bytes = src.getBytes();
            for (int i = 0; i < bytes.length; i += 2) {
                out.write( charToInt( bytes[i] ) * 16 + charToInt( bytes[i + 1] ) );
            }
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static int charToInt(byte ch) {
        int val = 0;
        if (ch >= 0x30 && ch <= 0x39) {
            val = ch - 0x30;
        } else if (ch >= 0x41 && ch <= 0x46) {
            val = ch - 0x41 + 10;
        }
        return val;
    }

    //创建文档
    public static String createDoc(String userid, List<Map<String, String>> list) {
        BaseBean log = new BaseBean();
        int docid = -1;
        String docids = "";
        DocServiceImpl docserviceimpl = new DocServiceImpl();
        String docsubject = ""; //文档标题
        String keyword = ""; //文档内容

        try {

            if (list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    DocAttachment[] docattachment = new DocAttachment[1];
                    Map<String, String> datamap = list.get( i );
                    String rawFileName = Util.null2String( datamap.get( "rawFileName" ) );
                    log.writeLog( "rawFileName:" + rawFileName );
                    String filetype = "";
                    log.writeLog( "rawFileName:" + rawFileName.lastIndexOf( "." ) );
                    if (rawFileName.lastIndexOf( "." ) > -1) {
                        filetype = rawFileName.substring( rawFileName.lastIndexOf( "." ) + 1 );
                    }
                    log.writeLog( "filetype:" + filetype );
                    String content = datamap.get( "content" );
                    //log.writeLog("content:"+content);
                    DocAttachment da = new DocAttachment();
                    da.setFilename( rawFileName );//附件标题
                    da.setFilecontent( content ); //附件内容
                    da.setFiletype( filetype ); //imagefiletype
                    da.setImagefilename( rawFileName );// 附件标题
                    da.setIszip( 1 );//是否压缩
                    da.setIsAesEncrype( 0 );//是否加密
                    da.setAesCode( "0" );
                    da.setIsextfile( "1" ); //附件是否是office类型

                    if (filetype.equalsIgnoreCase( "doc" )) {
                        da.setDocfiletype( "3" );
                    } else if (filetype.equalsIgnoreCase( "xls" )) {
                        da.setDocfiletype( "4" );
                    } else if (filetype.equalsIgnoreCase( "ppt" )) {
                        da.setDocfiletype( "5" );
                    } else if (filetype.equalsIgnoreCase( "wps" )) {
                        da.setDocfiletype( "6" );
                    } else if (filetype.equalsIgnoreCase( "docx" )) {
                        da.setDocfiletype( "7" );
                    } else if (filetype.equalsIgnoreCase( "xlsx" )) {
                        da.setDocfiletype( "8" );
                    } else if (filetype.equalsIgnoreCase( "pptx" )) {
                        da.setDocfiletype( "9" );
                    } else {
                        da.setDocfiletype( "2" );
                    }
                    docattachment[0] = da;
                    docsubject = rawFileName;
                    keyword = rawFileName;

                    DocInfo doc = new DocInfo(); //创建文档
                    doc.setMaincategory( 0 );//主目录id
                    doc.setSubcategory( 0 );//分目录id
                    doc.setSeccategory( 123 );//子目录id

                    doc.setDocSubject( docsubject );//标题
                    doc.setDoccontent( "" );//文档内容
                    doc.setKeyword( keyword );
                    doc.setAttachments( docattachment );
                    log.writeLog( "userid:" + userid );
                    if (!"".equals( userid )) {
                        User user = new User( Util.getIntValue( userid ) );
                        docid = docserviceimpl.createDocByUser( doc, user );
                        docids += docids == "" ? docid + "" : "," + docid;
                        log.writeLog( "docid:" + docid );
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.writeLog( "e:" + e );
        }
        log.writeLog( "docids:" + docids );
        return docids + "";
    }

    public static String getTime() {
        Calendar cal = Calendar.getInstance();
        cal.add( Calendar.DATE, 0 );
        Date date = cal.getTime();
        SimpleDateFormat sp = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
        String time = sp.format( date );//当天日期
        return time;
    }
    public static String getCurTime() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 0);
        Date date = cal.getTime();
        Date date1 = new Date(date.getTime() - 5 * 60 * 1000);
        SimpleDateFormat sp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sp.format(date1);//当天日期
        return time;
    }
    public static String getTimebefore() {
        RecordSet rs = new RecordSet();
        rs.executeQuery( "select curtime from syntimemail where id='1'" );
        rs.next();
        String time = Util.null2String( rs.getString( "curtime" ) );
        return time;
    }

    public static String getBeforeTime() {
        RecordSet rs = new RecordSet();
        rs.executeQuery( "select curtime from syntimedocinfo where id='1'" );
        rs.next();
        String time = Util.null2String( rs.getString( "curtime" ) );
        return time;
    }
    public static boolean createDir(String destDirName) {
        File dir = new File( destDirName );
        if (dir.exists()) {
            File[] files = dir.listFiles();
            if (files.length >= 1) {
                for (File fileToDel : files) {
                    fileToDel.delete();
                }

            }
            return false;
        }
        if (!destDirName.endsWith( File.separator )) {
            destDirName = destDirName + File.separator;
        }
        //创建目录
        if (dir.mkdirs()) {
            return true;
        } else {
            return false;
        }
    }

    //创建文件
    //（1）判断文件是否已经存在 （2）判断是不是目录（4）判断目录是否存在，不存在则创建（5）创建目标文件
    public static boolean createNewFile(String destFileName) {
        File file = new File( destFileName );
        if (file.exists()) {
            return false;
        }
        if (destFileName.endsWith( File.separator )) {
            return false;
        }
        //判断目标文件所在的目录是否存在
        if (!file.getParentFile().exists()) {
            //如果目标文件所在的目录不存在，则创建父目录
            if (!file.getParentFile().mkdirs()) {
                return false;
            }
        }
        //创建目标文件
        try {

            if (file.createNewFile()) {
                return true;
            } else {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static void getDoc2Clob(String filepath, String sql, String iszip, String sqlparam) {

        DataSource ds = (DataSource) StaticObj.getServiceByFullname( ("datasource.local"), DataSource.class );
        BaseBean bb = new BaseBean();
        Connection conn = null;
        try {
            conn = ds.getConnection();
            PreparedStatement pstm = conn.prepareStatement( sql );
            InputStream inputstream = null;
            ZipInputStream zin = null;
            File docfile = new File( filepath );
            if ("0".equals( iszip )) {
                inputstream = new BufferedInputStream( new FileInputStream( docfile ) );
            } else {
                zin = new ZipInputStream( new FileInputStream( docfile ) );
                if (zin.getNextEntry() != null) {
                    inputstream = new BufferedInputStream( zin );
                }
            }
            pstm.clearParameters();
            pstm.setBinaryStream( 1, inputstream );
            pstm.setString( 2, sqlparam );
            pstm.addBatch();
            pstm.executeBatch();
            if (inputstream != null || zin != null) {
                zin.close();
                inputstream.close();
            }
            conn.close();
        } catch (Exception e) {
            bb.writeLog( e.getMessage() );
        }
    }

    public static String getFilePath(String docid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery( "select filerealpath from imagefile where imagefileid in (select imagefileid from docimagefile where docid = '" + docid + "')" );
        rs.next();
        String filepath = Util.null2String( rs.getString( "filerealpath" ) );
        return filepath;
    }

    public static File doZip(String sourceDir, String zipFilePath, int needDelSource) {
        weaver.general.BaseBean baseBean = new weaver.general.BaseBean();
        File file = new File( sourceDir );
        File zipFile = new File( zipFilePath );
        ZipOutputStream zos = null;
        OutputStream os = null;
        BufferedOutputStream bos = null;
        if (!file.exists()) {
            return null;
        }
        try {
            // 创建写出流操作
            os = new FileOutputStream( zipFile );
            bos = new BufferedOutputStream( os );
            zos = new ZipOutputStream( bos );
            String basePath = null;
            // 获取目录
            if (file.isDirectory()) {
                basePath = file.getPath();
            } else {
                basePath = file.getParent();
            }
            zipFile( file, basePath, zos );

        } catch (IOException ex) {
            ex.printStackTrace();
            baseBean.writeLog( "IO异常：" + ex.toString() );
        } finally {
            try {
                if (needDelSource == 1) {
                    delFolder( sourceDir );
                }
                if (zos != null) {
                    zos.closeEntry();
                    zos.close();
                }
                if (bos != null) {
                    bos.close();
                }
                if (os != null) {
                    os.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
                baseBean.writeLog( "IO异常：" + e.toString() );
            }
        }
        return zipFile;
    }

    private static void zipFile(File source, String basePath, ZipOutputStream zos) {
        weaver.general.BaseBean baseBean = new weaver.general.BaseBean();
        File[] files = null;
        if (source.isDirectory()) {
            files = source.listFiles();
        } else {
            files = new File[1];
            files[0] = source;
        }
        InputStream is = null;
        String pathName;
        byte[] buf = new byte[1024];
        int length = 0;
        try {
            for (File file : files) {
                if (file.isDirectory()) {
                    pathName = file.getPath().substring( basePath.length() + 1 ) + "/";
                    zos.putNextEntry( new ZipEntry( pathName ) );
                    zipFile( file, basePath, zos );
                } else {
                    pathName = file.getPath().substring( basePath.length() + 1 );
                    is = new FileInputStream( file );
                    BufferedInputStream bis = new BufferedInputStream( is );
                    zos.putNextEntry( new ZipEntry( pathName ) );
                    while ((length = bis.read( buf )) > 0) {
                        zos.write( buf, 0, length );
                    }
                    if (bis != null) {
                        bis.close();
                    }
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
            baseBean.writeLog( "IO异常：" + ex.toString() );
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    baseBean.writeLog( "IO异常：" + e.toString() );
                }
            }
        }
    }

    public static boolean delFolder(String folderPath) {
        weaver.general.BaseBean baseBean = new weaver.general.BaseBean();
        if (StringUtils.isEmpty( folderPath )) {
            return Boolean.FALSE;
        }
        try {
            delAllFile( folderPath );  //删除完里面所有内容
            File myFilePath = new File( folderPath );
            if (myFilePath.exists()) {
                boolean result = myFilePath.delete();  //删除空文件夹
                //System.out.println( "---------------delete folder ------folderPath:"+folderPath);
                return result;
            }
        } catch (Exception e) {
            baseBean.writeLog( "删除文件夹操作出错" );
            e.printStackTrace();
            baseBean.writeLog( e.toString() );
        }
        return Boolean.FALSE;
    }

    /**
     * 删除文件
     *
     * @param path
     */
    public static void delAllFile(String path) {
        File file = new File( path );
        if (!file.exists()) {
            return;
        }
        if (!file.isDirectory()) {
            return;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith( File.separator )) {
                temp = new File( path + tempList[i] );
            } else {
                temp = new File( path + File.separator + tempList[i] );
            }
            if (temp.isFile()) {
                if (temp.exists()) {
                    temp.delete();
                }
            }
            if (temp.isDirectory()) {
                delAllFile( path + File.separator + tempList[i] );//先删除文件夹里面的文件
                delFolder( path + File.separator + tempList[i] );//再删除空文件夹
            }
        }

    }

    public static void main(String[] args) {
       String str = "12323";
       String [] arr = str.split(";");
        for (String s:arr) {
            System.out.println(s);
        }
        RecordSetDataSource ds1 = new RecordSetDataSource( "YaWei" );//外部数据源标识
        ds1.execute("");
    }
}

